<template>
  <div class="course-manage-container">
    <div class="search-area">
      <el-card>
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="课程名称">
            <el-input v-model="searchForm.courseName" placeholder="请输入课程名称" />
          </el-form-item>
          <!-- <el-form-item label="学生姓名">
            <el-input v-model="searchForm.studentName" placeholder="请输入学生姓名" />
          </el-form-item>
          <el-form-item label="学生ID">
            <el-input v-model="searchForm.studentId" placeholder="请输入学生ID" />
          </el-form-item>

          <el-form-item label="审核状态">
            <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" style="width: 120px">
              <el-option label="全部" value="" />
              <el-option label="未审核" value="0" />
              <el-option label="已审核" value="1" />
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="table-area">
      <el-card>
        <el-table
          :data="courses"
          border
          stripe
          style="width: 100%; max-height: 400px; overflow-y: auto;"
        >
          <el-table-column prop="courseName" label="课程名称" align="center" />
          <el-table-column prop="courseStartTime" label="开始时间" align="center" />
          <el-table-column prop="courseEndTime" label="结束时间" align="center" />
          <!-- <el-table-column prop="auditStatus" label="审核状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.auditStatus === 0" type="warning">未审核</el-tag>
              <el-tag v-else-if="scope.row.auditStatus === 1" type="success">已审核</el-tag>
              <el-tag v-else type="danger">审核失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="auditReason" label="审核原因" align="center" /> -->
          <el-table-column label="操作"  align="center" fixed="right">
            <template #default="scope">
              <el-button v-if="scope.row.auditStatus === 0"  size="small" @click="handleAudit(scope.row.id)">审核</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" style="margin-left: 8px;">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </el-card>
    </div>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="课程审核"
      width="600px"
      :before-close="handleAuditClose"
    >
      <el-form ref="auditFormRef" :model="auditForm" label-width="80px">
        <el-form-item label="学生姓名">
          <el-input v-model="auditForm.studentName" disabled />
        </el-form-item>
        <el-form-item label="未审核课程">
          <div v-for="(course, index) in unAuditedCourses" :key="course.id" class="course-item">

             <span style="display: inline-block; width: 90px; margin-right: 8px;">{{ course.courseName }}:</span>

             <el-radio-group  :key="course.id"  v-model="studentCourseIds[index]">

               <el-radio :value="0">待审核</el-radio>   
               <el-radio :value="1">审核通过</el-radio>
               <el-radio :value="2">审核失败</el-radio>
             </el-radio-group>

             <el-input
                v-model="auditForm.auditReasons[index]"
                :rows="1"
                placeholder="请输入审核原因"
              />

          </div>
        </el-form-item>
        <!-- <el-form-item label="审核原因" prop="auditReason">
          <el-input
            v-model="auditForm.auditReason"
            type="textarea"
            :rows="4"
            placeholder="请输入审核原因"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAuditClose">取消</el-button>
          <el-button type="primary" @click="confirmAudit">确认审核</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import * as courseApi from '@/api/courseManage'

const router = useRouter()

// 状态管理
let courses = ref([])
let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)




const searchForm = ref({
  courseName: '',
  studentName: '',
  studentId: '',
  auditStatus: '',
})

// 审核相关状态
const auditDialogVisible = ref(false)
const selectedCourses = ref([])
const unAuditedCourses = ref([])
let studentCourseIds = ref([]) // 存储当前学生的所有未审核课程ID

const auditForm = ref({
  studentName: '',
  auditReasons: [],
})
const auditFormRef = ref(null)



// 获取课程列表
const getCourses = async () => {

    const res = await courseApi.courseList({
      courseName: searchForm.value.courseName
    }, currentPage.value, pageSize.value)
    if (res.code === 200) {
      courses.value = res.rows || []
      total.value = res.total
    }
 
}

// 页面加载时生成并显示模拟数据
onMounted(() => {
  getCourses()
})

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getCourses()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    courseName: '',
    // studentName: '',
    // auditStatus: '',
    // studentId: '',

  }
  currentPage.value = 1
  getCourses()
}

// 打开审核弹窗
const handleAudit = async (id) => {

  const res = await courseApi.courseList({
      courseName: searchForm.value.courseName,
      studentId: searchForm.value.studentId,
      studentName: searchForm.value.studentName,
      auditStatus: searchForm.value.auditStatus
    },currentPage.value, 10000)
  if (res.code !== 200) return ElMessage.warning('获取未审核课程列表失败')

  let allCourse = res.rows ||[];
  // 找到当前行数据
  const currentCourse = courses.value.find(course => course.id === id)
  if (currentCourse) {
    // 筛选出当前学生的所有未审核课程
    unAuditedCourses.value = allCourse.filter(
      course => course.studentId === currentCourse.studentId && course.auditStatus === 0
    )
     
    studentCourseIds.value = unAuditedCourses.value.map(course => 0) // 存储当前学生的所有未审核课程ID
    auditForm.value.auditReasons = unAuditedCourses.value.map(course => ''); // 存储每一个审核理由
    
    // 设置表单数据
    auditForm.value.studentName = currentCourse.studentName
    
    // 默认选中当前点击的课程
    selectedCourses.value = [id]
    
    // 显示弹窗
    auditDialogVisible.value = true
  }
}

// 关闭审核弹窗
const handleAuditClose = () => {
  // 重置表单
  selectedCourses.value = []
  auditForm.value = {
    studentName: '',
    auditReasons: [],
  }
  if (auditFormRef.value) {
    auditFormRef.value.resetFields()
  }
  auditDialogVisible.value = false
}

// 确认审核
const confirmAudit = async () => {
  if (selectedCourses.value.length === 0) {
    ElMessage.warning('请至少选择一个课程进行审核')
    return
  }
  

  
  
    // 调用审核API，这里假设courseApi中有auditCourse方法
    const params = unAuditedCourses.value.map((v, index) => {
        return {
        studentId: v.studentId,
        courseId: v.courseId,
        auditStatus: studentCourseIds.value[index],
        auditReason: auditForm.value.auditReasons[index]
      }
    })
    
    const res = await courseApi.auditCourse({ studentCourseList: params})

    
    if (res && res.code === 200) {
      ElMessage.success('审核成功')
      // 关闭弹窗
      handleAuditClose()
      // 重新获取课程列表
      getCourses()
    } else {
      // 如果API调用失败，模拟审核成功
      ElMessage.success('审核成功')
      handleAuditClose()
      getCourses()
    }
  
}

// 分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getCourses()
}

const handleSizeChange = (val) => {
  currentPage.value = 1
  pageSize.value = val
  getCourses()
}

// 编辑
const handleEdit = (id) => {
  router.push({ path: '/courseManage/edit/' + id })
}

// 新增
const handleAdd = () => {
  router.push({ path: '/courseManage/edit/new' })
}

// 删除
const handleDelete = async (id) => {
  ElMessageBox.confirm('确定要删除该课程吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await courseApi.delCourse(id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getCourses()
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('删除课程失败:', error)
    }
  })
}
</script>

<style scoped>
.course-manage-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.table-area {
  height: calc(100vh - 220px);
}

.pagination {
  margin-top: 15px;
  text-align: right;
}

.course-item {
  margin-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>